package com.snailhd.framework.util.base;

import com.opencsv.CSVReader;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class CSVParser {

    public static  <T> List<T> parse(File file,String charsetName, Parser<T> parser,Integer skipHeader) throws Exception{
        CSVReader csvReader = new CSVReader((new InputStreamReader(new FileInputStream(file), charsetName)));
        return parse(csvReader,parser,skipHeader);
    }

    public static  <T> List<T> parse(InputStream is,String charsetName, Parser<T> parser,Integer skipHeader) throws Exception{
        CSVReader csvReader = new CSVReader((new InputStreamReader(is, charsetName)));
        return parse(csvReader,parser,skipHeader);
    }

    private static <T> List<T> parse(CSVReader csvReader, Parser<T> parser,Integer skipHeader) throws IOException {
        if(skipHeader!=null && skipHeader>0) {
            csvReader.skip(skipHeader);
        }
        List<String[]> rows = csvReader.readAll();
        List<T> result = new ArrayList<>(rows.size());
        for(String[] row:rows){
            T t = parser.parse(row);
            result.add(t);
        }
        return result;
    }


    public interface Parser<T>{
        T parse(String[] row);
    }

}
